package com.walle.gatewayserver.utils;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class GetParamsUtil {

	public static Map<String,?> getParams(RequestContext ctx){
		HttpServletRequest req = ctx.getRequest();
		Map<String, Object> map = new HashMap<>();
		
		Enumeration<String> names = req.getParameterNames(); 
		while (names.hasMoreElements()) { 
			String name = (String) names.nextElement(); 
			
			map.put(name, req.getParameter(name));
		} 
		
		
		if (!ctx.isChunkedRequestBody()) { 
			ServletInputStream inp = null; 
			try { 
				inp = ctx.getRequest().getInputStream(); 
				String body = null; 
				if (inp != null) { 
					body = IOUtils.toString(inp,Charsets.toCharset("utf-8")); 
					if(!StringUtils.isEmpty(body)) {
						
						try {
							Map m = (Map) JSON.parse(body);
							if(map!=null&&!m.isEmpty()) {
								map.putAll(m);
							}
						}catch(Exception e) {
							map.put("bodyParams", body);
						}
						
						
						
					}
				} 
				
			} catch (IOException e) { 
				
				log.error("======== 读取入参异常： url=[{}] ",req.getRequestURL().toString());
			} 
		}


		

		return map;

		
	}
	
}
